package com.jj.interceptor;


import com.alibaba.fastjson.JSONObject;
import com.jj.pojo.Result;
import com.jj.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
@Component
@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
//    在目标资源前执行的 方法
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
//        1.获取url
        String url = req.getRequestURL().toString();
        log.info("请求的url是：{}", url);
//        2.判断路径是否为登录
        if (url.contains("login")){
            log.info("登录操作，放行");
            return true;
        }
//       3.获取jwt令牌
        String jwt = req.getHeader("token");
//        4.判断令牌是否存在，如果存在，则进行解析，不存在则返回错误信息
        if (!StringUtils.hasLength(jwt)){
            log.info("令牌不存在");
            Result error = Result.error("NOT_LOGIN");
//            添加依赖，引入fastjson，将对象转为json
            String notLogin = JSONObject.toJSONString(error);
//            将JSON格式的错误信息写入响应体
            resp.getWriter().write(notLogin);
            return false;
        }
//        5.解析令牌
        try {
            JwtUtils.parseJWT(jwt);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌解析失败，拦截");
            Result error = Result.error("NOT_LOGIN");
//            添加依赖，引入fastjson，将对象转为json
            String notLogin = JSONObject.toJSONString(error);
//            将JSON格式的错误信息写入响应体
            resp.getWriter().write(notLogin);
            return false;
        }
//        6.放行
        log.info("放行");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle...");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion...");
    }
}
